import { Icon } from "@iconify/react";
import { Anchor } from "antd";
import MarkNav from "markdown-navbar";
import { useEffect, useState } from "react";

import styled from "styled-components";

const Styled = styled.div`
  header {
    display: flex;
    align-items: center;
    font-size: 6rem;
    span {
      margin-left: 10px;
    }
  }
`;

const addAnchor = () => {
  const ele = document.getElementsByClassName("markdown-body")[0];

  let eid = 0;
  let titles = [];

  //获取所有的标题
  for (const e of ele.childNodes) {
    if (
      e.nodeName === "H1" ||
      e.nodeName === "H2" ||
      e.nodeName === "H3" ||
      e.nodeName === "H4" ||
      e.nodeName === "H5" ||
      e.nodeName === "H6"
    ) {
      //锚点 id=#1 ，href=#1 这种
      let a = document.createElement("a");
      a.setAttribute("id", "#" + eid);
      a.setAttribute("class", "anchor-title");
      a.setAttribute("href", "#" + eid);
      a.innerText = " ";
      let title = {
        type: e.nodeName,
        id: eid,
        name: e.innerText,
      };
      titles.push(title);
      //往文章内容中出入锚点 需要判断，防止重复添加连接
      e.childNodes.length <= 1 && e.appendChild(a);
      eid++;
    }
  }
  return titles;
};
const Catalogue = ({ content }) => {
  const [titles, setTitles] = useState([]);

  const handleClickFun = (e, link) => {
    e.preventDefault();
    if (link.href) {
      // 找到锚点对应得的节点
      let element = document.getElementById(link.href);
      // 如果对应id的锚点存在，就跳滚动到锚点顶部
      element && element.scrollIntoView({ block: "start", behavior: "smooth" });
    }
  };

  useEffect(() => {
    setTitles(addAnchor());
  }, []);

  return (
    <Styled>
      <header>
        <Icon icon="typcn:th-menu-outline" />
        <span>目录</span>
      </header>
      {titles.length === 0 ? (
        <h1>空空如也</h1>
      ) : (
        <Anchor
          className="markdown-nav"
          affix={false}
          onClick={handleClickFun}
          getContainer={() => document.querySelector(".markdown-body")}
          items={titles.map((t) => {
            return {
              key: t.id,
              href: "#" + t.id,
              title: t.name,
            };
          })}
        ></Anchor>
      )}
    </Styled>
  );
};

export default Catalogue;
